package cn.dyw.shop.mapping;

import cn.dyw.shop.json.Json;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author: dyw770
 * @date: 2018/5/7
 */
@Controller
public class SystemMapping {

    @RequestMapping("/")
    public String index() {
        return "index";
    }

    @RequestMapping("/{url}")
    public String page(String url) {
        return url;
    }

    @ResponseBody
    @GetMapping("index/prc")
    public String[] indexPrc() {
        File file = new File("resources/index");
        String[] list = file.list();
        for (int i = 0; i < list.length; i++) {
            list[i] = "/resources/index/" + list[i];
        }
        return list;
    }

    @ResponseBody
    @PostMapping("/file/upload")
    public Json uploadImg(@RequestParam("file") MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
        File file1 = new File(  "H:/study/idea/shop/resources/upload/" + fileName);
        if (!file1.getParentFile().exists()) {
            file1.mkdirs();
        }
        if (file1.exists()) {
            try {
                file1.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            file.transferTo(file1);
        } catch (IOException e) {
            e.printStackTrace();
            return Json.factory(null, false, 1002, "fail");
        }
        return Json.factory("/resources/upload/" + fileName, true, 1001, "success");
    }
}
